//
//  FriendsContentVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/9/27.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "FriendsContentVC.h"
#import <JXCategoryView/JXCategoryView.h>
#import "SearchFriendResultVC.h"
#import "NewFriendListVC.h"
#import "AddressGroupVC.h"
#import "YCMenuView.h"
#import "DIYScanVC.h"
#import "FriendInfoListVC.h"
#import "GroupListVC.h"
#import "AddressListVC.h"
#import "BaseNavigationController.h"
#import "YBApiManager+Chat.h"
#import "SessionItem.h"
#import <LKDBHelper/LKDBHelper.h>
#import "ChatContentVC.h"
#import "UIViewController+ScanQR_Logic.h"
#import <WZLBadgeImport.h>

@interface FriendsContentVC ()<JXCategoryViewDelegate>

@property (nonatomic, strong) JXCategoryTitleView *topSegmentView;

@property (nonatomic, strong) UISearchController *searchVC;
@property (nonatomic, weak) SearchFriendResultVC *resultVC;
@property (nonatomic, assign) CFRunLoopObserverRef observerRef;
@property (nonatomic, strong) MASConstraint *searchBarContentLayoutForHeight;
@property (nonatomic, strong) MASConstraint *topViewLayoutForTop;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) NewFriendListVC *friendNewListVC;
@property (nonatomic, strong) AddressGroupVC *friendGroupListVC;
@property (nonatomic, strong) GroupListVC *groupChatListVC;
@property (nonatomic, strong) UIViewController *selectedVC;
@end

@implementation FriendsContentVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSearchVc];
    [self setupUI];
    [self setupSubViewControllers];
}

- (void)setupUI {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.k_img(UIImage.k_imgName(@"tab_plus"));
    [btn addTarget:self action:@selector(didClickRightBarBtnItemAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    UIView *topView = [[YBBaseView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 123)];

    
    self.topSegmentView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 30)];
    self.topSegmentView.titleColor = UIColor.k_t2Color;
    self.topSegmentView.averageCellSpacingEnabled = NO;
    self.topSegmentView.titleSelectedColor = UIColor.k_t2Color;
    self.topSegmentView.titleSelectedFont = [UIFont boldSystemFontOfSize:17];
    self.topSegmentView.titleFont = [UIFont systemFontOfSize:14];
    self.topSegmentView.defaultSelectedIndex = 2;
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorColor = UIColor.k_t1Color;
    lineView.indicatorWidth = 15;
    //可以试试宽度补偿
    //        lineView.indicatorWidthIncrement = 10;
    self.topSegmentView.indicators = @[lineView];
    self.topSegmentView.cellSpacing = 15;
    self.topSegmentView.delegate = self;
    self.topSegmentView.titles = @[@"新朋友", @"分组", @"群聊"];
    [topView addSubview:self.topSegmentView];
    
    UIView *cv = [[UIView alloc] initWithFrame:CGRectMake(0, 54, ScreenWidth, self.searchVC.searchBar.height)];
    [cv addSubview:self.searchVC.searchBar];
    [topView addSubview:cv];
    [self.view addSubview:topView];
    
    @weakify(self);
    topView.backgroundColor = UIColor.whiteColor;
    self.view.backgroundColor = self.navigationController.view.backgroundColor;
    [self.resultVC setViewWillPresentBlock:^{
        @strongify(self);
        self.view.backgroundColor = UIColor.whiteColor;
    }];
    [self.resultVC setViewWillDisPresentBlock:^{
        @strongify(self);
        self.view.backgroundColor = self.navigationController.view.backgroundColor;
    }];
    
    [self.topSegmentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.height.mas_equalTo(54);
    }];
    
    cv.backgroundColor = UIColor.whiteColor;
    [cv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        self.searchBarContentLayoutForHeight = make.top.equalTo(self.topSegmentView.mas_bottom);
         make.height.mas_equalTo(self.searchVC.searchBar.height);
        make.bottom.mas_offset(0);
    }];
//    self.searchVC.searchBar.
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        if (@available(iOS 11.0, *)) {
         self.topViewLayoutForTop = make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
        } else {
           self.topViewLayoutForTop = make.top.equalTo(self.view);
        }
    }];
    self.topView = topView;
    // 3.It is usually good to set the presentation context
    self.definesPresentationContext = YES;
}


- (void)setupSearchVc {
    
    self.extendedLayoutIncludesOpaqueBars = !self.navigationController.navigationBar.translucent;

    
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTintColor:UIColor.k_t2Color];
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[UISearchBar.class]] setTitle:@"取消"];
    
    @weakify(self);
    SearchFriendResultVC *resultVC = [SearchFriendResultVC new];
    [resultVC setViewWillPresentBlock:^{
        @strongify(self);
//        self.searchBarContentLayoutForHeight.offset(-self.searchVC.searchBar.height);
//        self.topViewLayoutForTop.offset(StatusBarHeight-15);
//        [self.view layoutIfNeeded];
        self.searchBarContentLayoutForHeight.offset(-self.searchVC.searchBar.height);
        [UIView animateWithDuration:0.25 animations:^{
            [self.view layoutIfNeeded];
        }];
    }];
    [resultVC setViewWillDisPresentBlock:^{
        @strongify(self);
        
//        self.topViewLayoutForTop.offset(0);
        self.searchBarContentLayoutForHeight.offset(-self.searchVC.searchBar.height);
        [UIView animateWithDuration:0.2 animations:^{
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            self.searchBarContentLayoutForHeight.offset(0);
            [UIView animateWithDuration:0.2 animations:^{
                [self.view layoutIfNeeded];
            }];
        }];
    }];
    [resultVC setDidSelectFriendItemBlock:^(FriendItem * _Nonnull item) {
        @strongify(self);
        [self showFriendInfoVCWithType:2 friendItem:item from:@"0"];
    }];
    self.resultVC = resultVC;
    self.searchVC = [[UISearchController alloc] initWithSearchResultsController:resultVC];
    
    self.searchVC.searchResultsUpdater = resultVC;
    self.searchVC.searchBar.delegate = resultVC;
    self.searchVC.delegate = resultVC;
    
    // 1.设置placeholder
    self.searchVC.searchBar.placeholder = @"搜索好友";
    
    // 2.设置searchBar的背景透明
    [self.searchVC.searchBar setBackgroundImage:UIImage.k_imgFillColor(UIColor.whiteColor, CGSizeMake(ScreenWidth, 64))];
    self.searchVC.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    // 3.设置搜索框文字的偏移
    self.searchVC.searchBar.searchTextPositionAdjustment = UIOffsetMake(3, 0);
    
    // 4.设置搜索框图标的偏移
    //    CGFloat offsetX = (self.view.bounds.size.width - 200 - 32) / 2;
    //    [self.searchVC.searchBar setPositionAdjustment:UIOffsetMake(offsetX, 0) forSearchBarIcon:UISearchBarIconSearch];
    
    // 5.取消按钮和文本框光标颜色
    //    self.searchVC.searchBar.tintColor = UIColor.k_t1Color;
    //    self.searchVC.searchBar.barTintColor = UIColor.k_t1Color;
    
    // 6.设置搜索文本框背景图片 [圆形的文本框只需要设置一张圆角图片就可以了]
    
    [self.searchVC.searchBar setSearchFieldBackgroundImage:[UIImage.k_imgFillColor(UIColor.k_hexColor(0xf0f0f0), CGSizeMake(ScreenWidth - 100, 36)) imageWithCornerRadius:36/2] forState:UIControlStateNormal];
    // 7.设置搜索按钮
    UIImage *searchImg = [[UIImage imageNamed:@"new_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [self.searchVC.searchBar setImage:searchImg forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    
    [self.searchVC.searchBar sizeToFit];
    
    
    // 2.Install the search bar
    //    if ([self.navigationItem respondsToSelector:@selector(setSearchController:)]) {
    //        // 2.1 For iOS 11 and later, wo place the search bar in the navigation bar
    //        if (@available(iOS 11.0, *)) {
    //            self.navigationItem.searchController = self.searchVC;
    //            // 2.2 Set the search bar visible all the time
    //            self.navigationItem.hidesSearchBarWhenScrolling = NO;
    //        }
    
    // 2.3 Hide line view
    //        __weak typeof(self) weakSelf = self;
    //        self.observerRef = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, kCFRunLoopAllActivities, true, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
    //
    //            NSLog(@"kCFRunLoopBeforeWaiting");
    //            BOOL targetView = [weakSelf barGroudView:weakSelf.navigationController.view];
    //            if (targetView) {
    //                CFRunLoopRemoveObserver(CFRunLoopGetMain(), observer, kCFRunLoopDefaultMode);
    //            }
    //        });
    //        CFRunLoopAddObserver(CFRunLoopGetMain(), self.observerRef, kCFRunLoopDefaultMode);
    
    //    } else {
   
  
    //    }
    
    
    
    // 8.拿到搜索文本框
    UITextField *searchField = [self.searchVC.searchBar valueForKey:@"_searchField"];
    //    // 9.设置取消按钮文字
    //    [self.searchVC.searchBar setValue:@"取消" forKey:@"_cancelButtonText"];
    //
    searchField.font = [UIFont systemFontOfSize:14];
}
- (BOOL)barGroudView:(UIView *)targetView {
    for (UIView *sView in targetView.subviews) {
        if ([sView isKindOfClass:NSClassFromString(@"_UINavigationControllerPaletteClippingView")]) {
            if (sView.subviews.count > 0 && sView.subviews[0].subviews.count > 0 && sView.subviews[0].subviews[0].subviews.count > 1) {
                sView.subviews[0].subviews[0].subviews[1].hidden = YES;
                return YES;
            }
        }
    }
    
    return NO;
}

- (void)setupSubViewControllers {
    self.friendNewListVC = [NewFriendListVC new];
    self.friendGroupListVC = [AddressGroupVC new];
    self.groupChatListVC = [GroupListVC new];
    
    [self addViewControler:self.groupChatListVC];
}
- (void)addViewControler:(UIViewController *)addVc {
    
    if (self.selectedVC) {
        [self.selectedVC.view removeFromSuperview];
        [self.selectedVC removeFromParentViewController];
    }
    
    self.selectedVC = addVc;
    [self addChildViewController:self.selectedVC];
    UIView *view = addVc.view;
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.equalTo(self.topView.mas_bottom);
    }];
    [self.view layoutIfNeeded];
}

#pragma mark - actions

- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {

    if (index == 0) {
        [self addViewControler:self.friendNewListVC];
        [self.friendNewListVC requestDatas];
        [self.tabBarItem clearBadge];
        [FileUtils deleteObjectFromUserDefaultWithKey:@"new_friend_agree"];
    } else if (index == 1) {
        [self addViewControler:self.friendGroupListVC];
    } else if (index == 2) {
        [self addViewControler:self.groupChatListVC];
    }

}

- (void)didClickRightBarBtnItemAction {
    
    @weakify(self);
    YCMenuAction *action1 = [YCMenuAction actionWithTitle:@"添加朋友" image:UIImage.k_imgName(@"new_add_normal") handler:^(YCMenuAction *action) {
        [self.navigationController pushViewController:[NSClassFromString(@"AddNewFriendVC") new] animated:YES];
    }];
    action1.highlightImage = UIImage.k_imgName(@"new_add_highlight");
    
    YCMenuAction *addGroupAction = [YCMenuAction actionWithTitle:@"发起群聊" image:UIImage.k_imgName(@"new_group_normal") handler:^(YCMenuAction *action) {
        AddressListVC *selectFriendVC = AddressListVC.new;
        selectFriendVC.listType = 2;
        [selectFriendVC setDidClickCreateGroupChatBlock:^(NSArray * _Nonnull ids) {
            NSLog(@"ids = %@", ids);
            @strongify(self);
            [self createGroupChatWithUserIds:ids];
        }];
        UINavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:selectFriendVC];
        [self presentViewController:nv animated:YES completion:nil];
    }];
    addGroupAction.highlightImage = UIImage.k_imgName(@"new_group_highlight");
    
    YCMenuAction *action2 = [YCMenuAction actionWithTitle:@"扫一扫" image:UIImage.k_imgName(@"new_qr_normal") handler:^(YCMenuAction *action) {
        @strongify(self);
        [self qr_showScanQRVC];
//        DIYScanVC *scanVC = [DIYScanVC new];
//
//        @strongify(self);
//        scanVC.scanResult = ^(NSString *result) {
//            [self showFriendInfoVCWithType:2 friendItem:[FriendItem mj_objectWithKeyValues:result] from:@"1"];
//        };
//        [self.navigationController pushViewController:scanVC animated:YES];
    }];
    action2.highlightImage = UIImage.k_imgName(@"new_qr_highlight");
    
    YCMenuView *view = [YCMenuView menuWithActions:@[action1, addGroupAction, action2] width:135 relyonView:self.navigationItem.rightBarButtonItem];
    view.textColor = UIColor.k_t2Color;
    
    [view show];
}
- (void)showFriendInfoVCWithType:(NSInteger)type friendItem:(FriendItem *)item from:(NSString *)from {
    FriendInfoListVC *VC = [FriendInfoListVC new];
    VC.user = item;
    VC.from = from;
    VC.listType = type;
    
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)createGroupChatWithUserIds:(NSArray *)ids {
    NSMutableString *userids = [[NSMutableString alloc] init];
    for (NSString *uid in ids) {
        [userids appendFormat:@"%@,",uid];
    }
    [userids deleteCharactersInRange:NSMakeRange(userids.length-1, 1)];
    @weakify(self);
    [[YBApiManager.shareManager createGroupChatWithGroupUserIds:userids] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [MBProgressHUD showActivityMessageInView:@""];
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInWindow:@"创建成功" timer:1.0f];
        [kUsermanager updateGroupChatList];
        NSDictionary *dataDic = [x objectForKey:@"data"];
        [self createGroupChatSuccessWithGroupInfo:dataDic];
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInWindow:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInWindow:@"网络错误，请重试" timer:1.0f];
        }
    }];
}

- (void)createGroupChatSuccessWithGroupInfo:(NSDictionary *)groupInfo {
    
    SessionItem *session = [SessionItem new];
    session.group_id = groupInfo[@"group_id"];
    session.groupIcon = groupInfo[@"avatar"];
    session.groupName = groupInfo[@"name"];
    session.isGroupChat = YES;
    [SessionItem insertToDB:session];
    
    ChatContentVC *chatVC = [ChatContentVC new];
    chatVC.session = session;
    [[NSNotificationCenter defaultCenter] postNotificationName:notification_NewSession_created object:session];
    [self.navigationController pushViewController:chatVC animated:YES];
}

@end
